home *** CD-ROM | disk | FTP | other *** search
- Path: news.clark.net!not-for-mail
- From: gusty@clark.net (Harlan Messinger)
- Newsgroups: comp.lang.c++
- Subject: Re: copy vs. assignment
- Date: 2 Mar 1996 17:23:04 GMT
- Organization: Clark Internet Services, Inc., Ellicott City, MD USA
- Message-ID: <4ha05o$7u8@clarknet.clark.net>
- References: <4h7va1$1ev@mother.usf.edu>
- NNTP-Posting-Host: explorer.clark.net
- Mime-Version: 1.0
- Content-Type: TEXT/PLAIN; charset=ISO-8859-1
- Content-Transfer-Encoding: 8bit
- X-Newsreader: TIN [UNIX 1.3 950726BETA PL0]
-
- Timothy Miller (millert@boheme.csee.usf.edu) wrote:
- : Well, it seems that overloading the = operator for assigning one instance
- : of a class to one of its own kind is futile, because no matter what, it
- : uses the copy constructor to copy the class.
-
- This is not true.
-
- :
- : My problem is that I need to do one thing if an object is initialized by
- : one of its own kind, like this;
- :
- : Matrix p;
- : // stuff done to p;
- : Matrix q = p; // <- right here
- :
- : And I need to do something else if an already existing object is being
- : assigned to like this:
- :
- : Matrix p, q;
- : // stuff done to p
- : q = p; // <- this should call a different class member
- :
- : No matter what I do, it seems that q gets initialized by the
- : constructor, regardless of whether or not it's already been created, even
- : if I overload the = operator.
-
- Then you must be doing something wrong. Even if you don't define
- operator= at all, the system will use the default operator= (memberwise
- copy) rather than your copy constructor.
-
- One possibility: perhaps you haven't set up the overload definition
- correctly. For example, if you have
-
- Matrix &operator =(Matrix M) {
- ...
- }
-
- then M, would be a "value" parameter. This means that M would be a newly
- constructed copy, local to your function and created using the copy
- constructor, of the matrix that was on the right side of the equals sign
- in the assignment statement. You would then be assigning from this copy,
- the result of which may look like the target matrix was itself set by the
- copy constructor.
-
- If this is the problem, the solution is to define the overload as
-
- Matrix &operator =(const Matrix& M) {
- ...
- }
-
- This makes M a "reference" parameter, which means that the function goes
- directly to the argument in the function call rather than making a copy
- of it. This keeps the copy constructor from being invoked, and eliminates
- the nuisance intermediate Matrix object created by a call-by-value.
-